package org.javaboy.yaml_demo.config;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.PropertySources;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.util.List;

@Configuration
public class WebConfig {
//    @Bean
//    PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
//        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
//        YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
//        yamlPropertiesFactoryBean.setResources(new ClassPathResource("user.yaml"));
//        configurer.setProperties(yamlPropertiesFactoryBean.getObject());
//        return configurer;
//    }
    @Bean
    PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        MutablePropertySources sources = new MutablePropertySources();
        YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
        try {
            List<PropertySource<?>> users = loader.load("user", new ClassPathResource("user.yaml"));
            List<PropertySource<?>> apps = loader.load("app", new ClassPathResource("application.yml"));
            for (PropertySource<?> user : users) {
                sources.addLast(user);
            }
            for (PropertySource<?> app : apps) {
                sources.addLast(app);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        configurer.setPropertySources(sources);
        return configurer;
    }

}
